import { createRef, RefObject } from 'react'
import type { Result } from 'ahooks/lib/useRequest/src/types'
import { produce } from 'immer'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { INotice, INoticeListReq } from './interface'

export type TRequest = Result<INotice[], [INoticeListReq]>

export interface IStore {
  gridRef: RefObject<AgGridReact<INotice>>
  request?: TRequest
  reqData: INoticeListReq
  setReqData: (noticeStatus: number | undefined, waybillNo?: string) => void
  getData: (scrollToTop?: boolean) => void
  changeNoticeStatus: (noticeId: number, noticeStatus: NonNullable<INotice['noticeStatus']>) => void
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    reqData: { noticeStatus: undefined, waybillNo: '' },
    setReqData: (noticeStatus, waybillNo) => {
      set(prev => ({ reqData: { ...prev.reqData, noticeStatus, waybillNo: waybillNo || prev.reqData.waybillNo } }))
    },
    getData: scrollToTop => {
      const { gridRef, request, reqData } = get()
      request?.run(reqData)
      if (scrollToTop) gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
    changeNoticeStatus: async (noticeId, noticeStatus) => {
      const mutate = get().request?.mutate
      mutate?.(oldData => {
        if (!oldData) return
        return produce(oldData, draft => {
          const target = draft.find(d => d.noticeId === noticeId)
          if (target) target.noticeStatus = noticeStatus
        })
      })
    },
  }
})
